<template>
	<div class="app_wraper" :class="{ close_dialog: closeDialogBool }"
		v-show="plateform == 'zhipin' || isBatchPage || pictureList.length || resumeData.name">
		<el-container id="resumeWrap" class="resume_wrap">
			<div class="resume_main" v-show="!closeDialogBool">
				<el-header id="dragHeader" class="rtitle" style="height: 30px">
					<em class="r_minus" @click="dialogClose(true)">隐藏</em>
					<h5>简历小助手</h5>
					<p class="ainfo">
						<img v-if="userInfo && userInfo.avatar" class="uhead" :src="userInfo && userInfo.avatar" />
						<span v-if="userInfo && userInfo.nickname">{{ userInfo && userInfo.nickname }}</span>
					</p>

				</el-header>
				<!-- 智联卓聘下选择公司 START -->
				<template v-if="isBatchPage || isDev">
					<p class="relation relation2">
						<!-- <span class="rtit">关联公司：</span> -->
						<el-input size="mini" :disabled="matchStatus == 1" @change="companyNameChange"
							@blur="companyNameChange" v-model="companyName"
							:class="{ vselect: true, company: true, hasrelation: companyID }" placeholder="公司名称" />

						<el-button v-if="!matchStatus || matchStatus == 0" @click="matchBtn" type="primary"
							size="mini">开始匹配</el-button>
						<el-button v-else-if="matchStatus == 1" @click="stopMatchBtn" type="danger"
							size="mini">结束匹配</el-button>
						<el-button v-else-if="matchStatus == 2" type="info" size="mini">已结束</el-button>
					</p>
				</template>
				<!-- 智联卓聘下选择公司 END -->
				<template v-if="resumeData && resumeData.name">
					<el-main class="rwrap" v-loading="loading || loading1 || loading2">
						<p class="relation">
							<el-input size="mini" @blur="companyNameChange" v-model="companyName"
								:class="{ vselect: true, company: true, hasrelation: companyID }" placeholder="公司名称" />
							<v-select :class="{ vselect: true, talent: true, hasrelation: relationID }"
								placeholder="用户姓名" :options="talentList" v-model="relationID" @search="searchTalent"
								@input="relationBlur" @option:selected="relationChange">
								<template #option="{ _id, name, company_name, job, from }">
									<p class="otext">
										<span v-if="from == 'liepin'">猎聘</span>
										<span v-else-if="from == 'patent'">专利</span>
										<span v-else-if="from == 'doctor'">论文</span>
										<span v-else-if="from == 'zhaopin'">智联</span>
										<span v-else-if="from == 'maimai'">脉脉</span>#<a class="blue"
											@click="navToResume({ _id })">{{ name
											}}</a>#{{ company_name }}#{{ job }}
									</p>
								</template>
								<template #no-options>
									<p class="dtext">无匹配人才</p>
								</template>
							</v-select>
						</p>

						<!-- 查找到多份 简历 START -->
						<template v-if="repeatBool && listBool && !relationID">
							<el-descriptions class="similar" size="mini" :column="6">
								<!--  -->
								<template slot="title">
									<p class="rstatus">
										当前共查询到<em>{{ similarList.length }}</em>份类似简历
									</p>
								</template>
								<template slot="extra">
									<a class="refresh" @click="repeatBtn" alt="点击刷新">刷新</a>
									<!-- <img class="refresh" src="@/static/img/refresh.png" style="cursor: pointer" @click="repeatBtn" /> -->
								</template>
								<!-- 搜索到的简历列表 START -->
								<template v-for="(item, index) in similarList">
									<el-descriptions-item :span="6"  labelClassName="split_line"
										contentClassName="split_content"> </el-descriptions-item>
									<el-descriptions-item label="头像" :span="4">
										<img :src="item.avatar" alt="" class="avatar" />
									</el-descriptions-item>
									<el-descriptions-item label="来源" :span="2"
										v-if="item.plateform">
										{{ item.plateform }}
									</el-descriptions-item>
									<el-descriptions-item label="姓名" :span="4">
										{{ item.name }}
									</el-descriptions-item>
									<el-descriptions-item label="性别" :span="2">
										{{ item.sex == 1 ? '男' : item.sex == 2 ? '女' : '-' }}
									</el-descriptions-item>
									<!-- <el-descriptions-item label="年龄" :span="2" :key="index">
              {{ item.age }}
            </el-descriptions-item> -->
									<el-descriptions-item label="毕业院校" :span="6"
										v-if="item.educate && item.educate[0] && item.educate[0].name" :key="index">{{
											item.educate[0].name
										}}·{{ similarData.educate && similarData.educate[0].special
										}}</el-descriptions-item>
									<el-descriptions-item label="公司名称" :span="6" v-if="item.company_name"
										:key="index">{{
											item.company_name
											|| '-' }}</el-descriptions-item>
									<el-descriptions-item label="岗位名称" :span="4" v-if="item.company_name || item.job"
										:key="index">{{
											item.job || '-' }}</el-descriptions-item>
									<el-descriptions-item label="操作" :span="2" :key="index"><a class="view_btn"
											@click="viewBtn(item)">查看</a></el-descriptions-item>
								</template>
								<!-- 搜索到的简历列表 END -->
							</el-descriptions>
							<el-button :class="{ disable: loading }" class="btn3 btn sbtn" @click="exportBtn"
								:loading="loading1">都不匹配，导入简历</el-button>
						</template>

						<!-- 查找到多份 简历 END -->
						<template v-else-if="repeatBool && (!listBool || relationID)">
							<el-descriptions class="similar" size="mini" :column="5">
								<!--  -->
								<template v-if="similarList.length > 1 && !relationID" slot="title"><span
										class="back_btn" @click="backBtn">&larr;返回 </span></template>
								<!-- <template v-if="similarList.length == 1" slot="title"> 查询到相似简历 </template>
          <template v-if="similarList.length == 1" slot="extra">
            <a class="refresh" @click="repeatBtn" alt="点击刷新">刷新</a>
          </template> -->
								<!-- <el-descriptions-item :span="6" labelClassName="split_line" contentClassName="split_content"> </el-descriptions-item> -->
								<el-descriptions-item label="头像" :span="3" v-if="similarData.avatar">
									<img :src="similarData.avatar" alt="" class="avatar" />
								</el-descriptions-item>
								<el-descriptions-item label="来源" :span="similarData.avatar ? 2 : 5"
									v-if="similarData.plateform">
									{{ similarData.plateform }}
								</el-descriptions-item>
								<el-descriptions-item label="姓名" :span="2"><a @click="navToResume(similarData)">{{
									similarData.name
								}}</a></el-descriptions-item>
								<el-descriptions-item label="电话" :span="3">{{ similarData.mobile || '-'
								}}</el-descriptions-item>

								<el-descriptions-item label="公司名称" :span="5">{{ similarData.company_name
								}}</el-descriptions-item>
								<el-descriptions-item label="岗位名称" :span="5">{{ similarData.job
								}}</el-descriptions-item>
								<el-descriptions-item label="毕业院校" :span="5">{{
									similarData.educate && similarData.educate[0] && similarData.educate[0].name
								}}·{{ similarData.educate && similarData.educate[0] &&
										similarData.educate[0].special
									}}</el-descriptions-item>
								<el-descriptions-item label="创建人" :span="2">{{ similarData.username
								}}</el-descriptions-item>
								<el-descriptions-item label="创建时间" :span="3">{{ similarData.createTime
								}}</el-descriptions-item>
								<el-descriptions-item label="项目" :span="5" v-if="similarData._id">
									<a @click="navToProject(pro)" style="margin-right:5px;" v-for="pro in project_list"
										:key="pro._id">{{ pro.name
										}}</a>
									<el-button class="btn_mini" size="mini" @click="joinProjectBtn">加入项目</el-button>
									<el-button class="btn_mini btn_mini2" size="mini"
										@click="joinCallBtn">添加回访</el-button>
								</el-descriptions-item>
								<el-descriptions-item label="跟进" :span="5" v-if="similarData.promot_content">{{
									similarData.promot_content
								}}【{{ similarData.timestamp }}】</el-descriptions-item>
							</el-descriptions>

							<p class="sinfo" v-if="similarData.flag">
								<em></em>有相似的
								{{ similarData.flag.name ? '姓名、' : '' }}
								{{ similarData.flag.sex ? '性别、' : '' }}
								{{ similarData.flag.born ? '年龄、' : '' }}
								{{ similarData.flag.company ? '公司经历、' : '' }}
								{{ similarData.flag.educate ? '毕业院校' : '' }}
							</p>
						</template>
						<!-- 未查询到相似简历 START -->
						<template v-else>
							<el-empty>
								<template slot="description"> 未查询到相似简历<a class="refresh" style="margin-left: 4px"
										@click="repeatBtn">刷新</a></template>
							</el-empty>
						</template>
						<!-- 未查询到相似简历 END -->
					</el-main>
					<el-footer class="actwrap" style="height: 40px" v-show="!repeatBool || !listBool">
						<template v-if="repeatBool">
							<el-button :class="{ disable: loading }" class="btn1 btn" @click="exportBtn"
								:loading="loading1">导入简历</el-button>
							<el-button :class="{ disable: loading }" class="btn2 btn" @click="updateBtn"
								:loading="loading2">更新简历</el-button>
						</template>
						<template v-else>
							<el-button :class="{ disable: loading }" class="btn3 btn" @click="exportBtn"
								:loading="loading1">导入简历</el-button>
						</template>
					</el-footer>
				</template>
				<div class="picture_wraper" :class="{ picture_close: closePictureBool }" v-if="pictureList.length">
					<!-- <el-collapse v-model="activeIndex" class="p_collapse">
          <el-collapse-item name="1">
            <template slot="title">
              <div class="ptitle">候选人标签</div>
            </template>
            <ul class="piclist">
              <li v-for="(item, index) in pictureList" :key="index">
                <span>{{ item.name }} :</span>
                <em v-for="(pic, idx2) in item.children" :key="index + '_' + idx2">{{ pic.name }}</em
                >&ensp;
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse> -->
					<div class="ptitle">
						候选人标签
						<div class="p_close" @click="pictureActBtn">{{ closePictureBool ? '展开' : '收起' }}</div>
					</div>
					<ul class="piclist">
						<li v-for="(item, index) in pictureList" :key="index">
							<span>{{ item.name }} :</span>
							<em v-for="(pic, idx2) in item.children" :key="index + '_' + idx2">{{ pic.name }}</em>&ensp;
						</li>
					</ul>

				</div>
			</div>
			<div class="r_open" @click="dialogClose(false)">展开助手</div>
		</el-container>
		<el-dialog width="40%" title="选择项目" :visible.sync="projectBool" append-to-body>
			<el-select v-if="plateform != 'zhaopin'" :multiple="false" filterable placeholder="请选择要加入的项目"
				v-model="projectID" style="width:100%">
				<el-option v-for="item in projectList" :key="item._id"
					:label="item.name + '#' + item.company_name || ''" :value="item._id">
				</el-option>
			</el-select>
			<select v-else searchable filterable class="pselect" v-model="projectID">
				<option value="">====请选择===</option>
				<option v-for="item in projectList" :key="item._id" :value="item._id">
					{{ item.name + '#' + item.company_name || '' }}
				</option>
			</select>
			<!-- <v-select placeholder="请选择要加入的项目" :options="projectList" v-model="projectID" @search="searchProject"
				@input="projectBlur" @option:selected="projectChange">
				<template #option="{ _id, name, company_name }">
					<p class="otext">
						<a class="blue" @click.stop="navToProject({ _id })">{{
							name
						}}</a>#{{ company_name }}
					</p>
				</template>
				<template #no-options>
					<p class="dtext">无匹配项目</p>
				</template>
			</v-select> -->
			<span slot="footer" class="dialog-footer">
				<el-button size="mini" @click="projectBool = false">取 消</el-button>
				<el-button size="mini" type="primary" @click="confirmProjectBtn">确 定</el-button>
			</span>
		</el-dialog>
		<el-dialog width="40%" title="添加回访记录" :visible.sync="callBool" append-to-body>
			<el-input v-model="callValue" :rows="8" type="textarea" placeholder="请输入回访记录内容" />
			<span slot="footer" class="dialog-footer">
				<el-button size="mini" @click="callBool = false">取 消</el-button>
				<el-button size="mini" type="primary" @click="confirmCallBtn" :loading="calling">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
import $, { error } from 'jquery';
import 'jquery-ui-dist/jquery-ui';
import baseCompent from 'service/baseCompent.js';
import _ from 'underscore';
import ajaxService from 'service/service.js';
import moment from 'moment';
var resumeData = {
	"link": "https://h.zhaopin.com/zphunter/resume/detail?cvId=5537765&resumeNumber=V%29rk8ohsWqG2mFRDFQBAJrxeXH%2939tc9",
	"avatar": "https://mypics.zhaopin.cn//pic/2016/6/26/baa7419d-2a86-46ca-9ffc-87705f8887b0.jpg",
	"name": "黄伟",
	"sex": "1",
	"born": 557420400000,
	"status": "在职-正在找工作",
	"target": [{
		"job": "销售顾问",
		"salary": "15000-25000元/月",
		"city": "西安",
		"industry": "汽车研发/制造"
	},
	{
		"job": "机械设计/制造",
		"salary": "15000-25000元/月",
		"city": "西安",
		"industry": "汽车研发/制造"
	}
	],
	"educateList": [{
		"name": "长安大学",
		"special": "交通工程",
		"degree": "本科",
		"time": [
			1188576000000,
			1309449600000
		],
		"tags": [
			"211"
		]
	}],
	"job": "换代项目内饰设计师",
	"companyList": [{
		"name": "陕西重汽研究院",
		"service": [
			"汽车研发/制造"
		],
		"tags": [],
		"time": [
			1404144000000
		],
		"job": "换代项目内饰设计师",
		"work": "从事陕重汽全新一代产品内饰的设计开发工作，工作内容主要包含：①内饰的平台规划，确定不同车型的内饰配置需求；②对造型部门提供的内饰CAS面进行校核，主要确认内饰的分块可行性，和工艺可行性；③对内饰零件进行安装点布置，确定与车身的安装位置及安装断面图；④进行内饰零件的详细结构设计工作；⑤完成CNC样件数据，进行装车检证，问题整改；⑥开模数据完成。"
	},
	{
		"name": "公司名称未填写",
		"service": [
			"互联网"
		],
		"tags": [],
		"time": [
			1404144000000
		],
		"job": "",
		"work": ""
	},
	{
		"name": "公司名称未填写",
		"service": [
			"互联网"
		],
		"tags": [],
		"time": [
			1309449600000,
			1404144000000
		],
		"job": "",
		"work": ""
	},
	{
		"name": "东风本田汽车有限公司",
		"service": [
			"汽车研发/制造"
		],
		"tags": [],
		"time": [
			1306857600000,
			1404144000000
		],
		"job": "新车型引进内饰工艺工程师",
		"work": "新车型引进项目组主要业务为新车型由试制导入量产的生产线工艺编排，生产准备，零部件装配特性检证和品质提升等工作。我主要负责内饰领域，主要工作内容有：①新车型内饰领域的工艺编排，编制作业标准书和品质基准表。②参与新车型试制，对于装配工艺进行检证和生产线工艺优化。②内饰线的品质问题反馈与跟踪，重点推进装配不良。③参与产品设计阶段的零部件装配工艺校核，对易发生装配不良和其他方面的质量问题提出整改要求，以提升产品的装配品质。④共参与过思域、CR-V，杰德，思铂睿、艾力绅共5款车型的新车型导入工作，并且担纲CR-V中期改款的总装工艺总负责人。"
	}
	],
	"projectList": [{
		"name": "中期改款CRV导入",
		"time": [
			1380556800000,
			1404144000000
		],
		"work": "负责CRV导入总装领域的计划编制，项目协调和整体推进"
	},
	{
		"name": "新概念车型杰德导入",
		"time": [
			1335801600000,
			1362067200000
		],
		"work": "负责杰德的内饰工艺编排和质量推进工作。"
	},
	{
		"name": "第9代思域新车型导入",
		"time": [
			1309449600000,
			1317398400000
		],
		"work": "负责第九代思域内饰工艺的工程编排和作业品质指导书编制。"
	}
	],
	"evaluation": "2011年7月从大学毕业至今，我有了3年的合资企业制造管理的经验和2年自主品牌企业开发设计的经验，我能够胜任汽车企业制造管理，研究开发和采购售后的工作。作为一个汽车人，我也热切期望能够在新的岗位上发光发热。\r\n",
	"language": [
		"英语"
	],
	"credential": [
		"大学英语六级"
	]
};
export default {
	extends: baseCompent,
	data() {
		return {
			plateform: '',
			isDev: process.env.NODE_ENV != 'production',
			matchStatus: 0,
			projectBool: false,//选择项目弹窗是否显示
			callBool: false,//添加回访记录
			calling: false,
			callValue: '',
			closeDialogBool: false,//选择人才弹窗是否显示
			closePictureBool: false,//选择人才弹窗是否显示
			projectList: [],//项目列表
			projectID: '',//
			urlValue: window.location.href, //当前页面URL地址，用于判断是否
			isBatchPage: window.location.href.includes('maimai.cn/web/search_center') || window.location.href.includes(
				'h.zhaopin.com/zphunter/talent/search') || window.location.href.includes(
					'maimai.cn/ent/v41/recruit/talents') ? true : false,
			loading: true,
			loading1: false,
			loading2: false,
			activeIndex: ['1'],
			pictureList: [],
			resumeData: {},
			similarList: [],
			similarData: {},
			project_list: [],
			similarDataBack: {},
			listBool: false,
			from: 'maimai',
			repeatBool: false,
			remoteCLoading: false,
			remoteLoading: false,
			companyID: '',
			companyName: '',
			vcompanys: [],
			relationID: '',
			companyList: [],
			talentList: [],
			userInfo: {
				//nickname: '蒋秀川',
				//user_id: '66d0388b8620664def49922b'//管理员
				user_id: '66da5e8299c624f04fbb3e81'//顾问
				//avatar: 'https://i9.taou.com/maimai/p/36008/6753_125_37T8xRf3RXBzfF9J-a160'
			}
		};
	},
	watch: {
		similarData(similar) {
			this.getTalentProject(similar._id);
		}
	},
	methods: {
		dialogClose(value) {
			this.closeDialogBool = value;
			localStorage.setItem('closeDialogBool', value);
		},
		pictureActBtn() {
			this.closePictureBool = this.closePictureBool ? false : true;
			localStorage.setItem('closePictureBool', this.closePictureBool);
		},
		dealSimilar(data) {
			const promot_list = data.promot_list || [];

			if (promot_list && promot_list.length > 0) {
				let time = '', promot_content = '';
				_.each(promot_list, promot => {
					if (promot.timestamp > time) {
						time = promot.timestamp;
						promot_content = promot.content;
					}
				})
				data.promot_content = promot_content;
				data.timestamp = time;
			}
			return data;
		},
		getRemoteCompany(name = '') {
			return ajaxService.getRemoteCList({
				name: {
					op: 'like',
					value: name.trim()
				}
			});
		},
		async matchBtn() {
			const that = this;
			if (!this.companyName || !this.companyName.trim()) {
				return this.$message.error('请输入要关联的公司名称');
			}
			if (this.companyName.trim().length < 2) {
				return this.$message.error('公司名称过短');
			}
			if (that.loading2) return false;
			that.loading2 = true;
			const result = await that.getRemoteCompany(this.companyName);
			that.loading2 = false;
			if (result && result.data.length > 400) {
				return this.$message.error('关联公司过多，请重试');
			}
			that.vcompanys = result.data;
			const company_ids = that.vcompanys?.map((item) => item._id);
			if (!company_ids || company_ids?.length == 0) {
				return this.$message.error('未查询到要关联的公司');
			}
			window.postMessage({
				type: 'talent_match',
				data: {
					company_id: company_ids.join(',')
				}
			},
				'*'
			);
			this.matchStatus = 1;
			this.stopByUserBool = false;
			//this.$message.success('已发送关联请求！');
		},
		stopMatchBtn() {
			const company_ids = this.vcompanys.map((item) => item._id).join(',');
			window.postMessage({
				type: 'stop_talent_match',
				data: {
					company_id: company_ids
				}
			},
				'*'
			);
			this.stopByUserBool = true;
			this.$message.success('关联结束！');
			this.matchStatus = 2;
		},
		matchOver() {
			if (this.stopByUserBool) return false;
			this.$message.success('关联结束！');
			this.matchStatus = 2;

		},
		postCheckOver() {
			window.postMessage({
				type: 'check_talent_end'
			},
				'*'
			);
		},
		async joinProjectBtn() {
			this.projectBool = true;
			const list = await ajaxService.getProjects({ uid: this.userInfo?.user_id });
			this.projectList = list.sort((item1, item2) => {
				//console.log(item1,item2);
				return item2.sort - item1.sort;
			});
		},

		async confirmProjectBtn() {
			if (!this.projectID) return this.$message.error('请选择要加入的项目')
			const result = await ajaxService.joinProject({ from: 'talent', uid: this.userInfo?.user_id, project_id: this.projectID, talent_id: this.similarData._id });
			if (result && result.code != 1000) {
				return this.$message.error(result.message)
			}
			this.$message.success(result.message);
			this.projectBool = false;
			//this.projectID = '';
			this.getTalentProject(this.similarData._id);
		},
		joinCallBtn() {
			this.callBool = true;
		},
		async confirmCallBtn() {
			if (!this.callValue.trim()) return this.$message.error('请输入回访内容');
			this.calling = true;
			const result = await ajaxService.addCallback({ uid: this.userInfo?.user_id, talent_id: this.similarData._id, content: this.callValue });
			if (result && result.code != 1000) {
				return this.$message.error(result.message)
			}
			this.similarData.promot_list = result.data.promot_list;
			this.calling = false;
			this.$message.success(result.message);
			this.callBool = false;
			this.callValue = '';
			this.similarData = this.dealSimilar(this.similarData);
			//this.getTalentProject(this.similarData._id);
		},
		searchProject: _.debounce(async (name) => {
			const that = window.painter;
			const list = await ajaxService.getProjects({ uid: that.userInfo?.user_id, name });
			this.projectList = list.sort((item1, item2) => {
				return item2.sort - item1.sort;
			});
		}, 300),
		async getLocal(key) {
			/* eslint-disable no-undef */
			const result = await chrome.storage.local.get([key]);
			return result[key];
			/* eslint-enable no-undef */
		},
		getRemoteCList(value, op = 'like') {
			//console.log('开始获取远程数据信息！！！！！', value);
			this.remoteCLoading = true;
			//console.log('开始加载简历列表！！！');
			ajaxService
				.getRemoteCList({
					key: 'name',
					value,
					op
				})
				.then((list) => {
					//console.log('获取远程数据返回信息！！！！！', res);
					this.companyList = (list.data || [])?.map((item) => {
						item.label = item.name;
						return item;
					});
					this.remoteCLoading = false;
				});
		},
		getRemoteList(value, op = 'like') {
			//console.log('开始获取远程数据信息！！！！！', value);
			// if (!this.companyID) {
			//   return false;
			// }
			const param = {};
			if (value) {
				param.name = {
					value,
					op
				};
			}
			if (this.companyID) {
				param.company_id = {
					value: this.companyID._id,
					op: 'eq'
				};
			}
			this.loadTalentList(param);
		},
		loadTalentList(param) {
			this.remoteLoading = true;
			if (this.companyName && this.companyName.trim()) {
				param.company_name = this.companyName.trim();
			}
			//console.log('开始加载简历列表！！！');
			ajaxService.getRemoteList2(param).then((list) => {
				this.talentList = (list.data || [])?.map((item) => {
					item.label = item.name + '#' + item.company_name;
					return item;
				});
				this.remoteLoading = false;
			});
		},
		sleep(time = 0) {
			return new Promise((resolve) => {
				setTimeout(() => {
					resolve();
				}, time);
			});
		},
		searchTalent: _.debounce((value) => {
			window.painter.getRemoteList(value)
		}, 300),
		async relationBlur() {
			await this.sleep(1000);
			if (!this.relationID) {
				this.getRemoteList();
			}
		},
		companyNameChange() {
			if (!this.companyName || !this.companyName.trim()) {
				return false;
			}
			if (this.matchStatus == 2) {
				this.matchStatus = 0;
			}

		},
		relationChange() {
			if (!this.relationID || !this.relationID._id) {
				this.similarData = this.dealSimilar(this.similarDataBack);
				this.tid = this.getUrlParam('fromuid', this.resumeData.link);
				this.getRemoteList();
				this.repeatBtn();
				return false;
			}
			const similarData = _.findWhere(this.talentList, {
				_id: this.relationID._id
			});
			this.similarData = this.dealSimilar(similarData);
			this.tid = this.similarData._id;
			this.repeatBtn('select');
		},
		/*
强制推送简历到系统
*/
		forceUpload() {
			this.force = false;
			this.upload(this.similarData?._id, {
				from: this.pictureFrom,
				_id: this.pictureId
			});
		},
		async getTalentProject(talent_id) {
			const result = await ajaxService.getTalentProject({ _id: talent_id })
			if (this.similarData._id == talent_id) {
				this.project_list = result || [];

			} else {
				this.project_list = [];
			}

		},
		exportBtn() {
			this.upload();
			// this.$confirm('此操作将会创建一条新的简历数据, 是否继续?', '提示', {
			//   confirmButtonText: '确定',
			//   cancelButtonText: '取消',
			//   type: 'warning'
			// })
			//   .then(() => {
			//     this.upload();
			//   })
			//   .catch(() => {
			//     this.$message({
			//       type: 'info',
			//       message: '取消导入'
			//     });
			//   });
		},
		upload(_id, extra) {
			this.loading1 = true;
			const name = $('body').data('name');
			const resume = this.resumeData;
			if (name) {
				resume.name = name;
			}
			_id && (resume._id = _id);
			//delete resume.extra;
			const postData = {
				resume,
				uid: this.userInfo?.user_id,
				from: this.from,
				extra
			};
			ajaxService.uploadResume(postData).then((res) => {
				this.loading1 = false;
				if (res._id) {
					this.tid = res._id;
					this.resumeData._id = res._id;
				}
				if (res.result) {
					this.$message({
						type: 'success',
						message: (_id ? '更新' : '导入') + '成功!'
					});
					this.repeatBtn();
					console.log('上传简历返回响应信息！！！！！', res);
				} else {
					this.$message({
						type: 'error',
						message: (_id ? '更新' : '导入') + '失败!'
					});
				}
				this.postCheckOver();
			}, error => {
				this.loading1 = false;
				if (_id) {
					return this.$message({
						type: 'error',
						message: '更新失败!'
					});
				} else {
					delete this.resumeData.extra;
					this.upload();
				}
			});
		},
		updateBtn() {
			this.upload(this.similarData._id);
			// this.$confirm('此操作将会更新上面的相似简历数据, 是否继续?', '提示', {
			//   confirmButtonText: '更新',
			//   cancelButtonText: '取消',
			//   type: 'warning'
			// })
			//   .then(() => {
			//     this.upload(this.similarData._id);
			//   })
			//   .catch(() => {
			//     this.$message({
			//       type: 'info',
			//       message: '取消更新'
			//     });
			//   });
			//if(this.loading)return false;
		},
		dateFormat(time, format = 'YYYY-MM-DD') {
			return moment(time).format(format);
		},
		viewBtn(data) {
			this.similarData = this.dealSimilar(data);
			this.similarDataBack = data;
			this.listBool = false;
		},
		backBtn() {
			this.similarData = {};
			this.listBool = true;
		},
		repeatBtn(from = 'inside') {
			this.loading = true;
			const resume = Object.assign({}, this.resumeData);
			const tid = this.tid || '';
			delete resume.extra;
			const params = {
				resume,
				tid,
				from: this.from
			};
			ajaxService.repeatResume(params).then((similar) => {
				this.loading = false;
				this.repeatBool = !_.isEmpty(similar) ? true : false;
				this.similarList = _.isArray(similar) && (similar || []).map((item) => {
					item.age = item.born ? this.getAge(item.born) : '-';
					item.createTime = this.dateFormat(item.create_date);
					if (item.from == 'maimai') {
						item.plateform = '脉脉';
					} else if (item.from == 'liepin') {
						item.plateform = '猎聘';
					} else if (item.from == 'zhipin') {
						item.plateform = 'BOSS';
					} else if (item.from == 'zhaopin') {
						item.plateform = '智联';
					} else {
						item.plateform = '其他';
					}
					return item;
				}) || [];
				//this.similarList = [...this.similarList, ...this.similarList];
				if (this.similarList.length == 1) {
					this.similarData = this.dealSimilar(this.similarList[0]);
					this.listBool = false;
				} else {
					this.similarData = {};
					this.listBool = true;
				}
				if (from !== 'select') {
					this.similarDataBack = this.similarList?.[0];
				}
				/****************如果force=true 执行强制推送************************/
				this.force && this.forceUpload();
			});
		},
		getAge(timestamp) {
			return parseInt(moment(timestamp).toNow(true));
		},
		getUrlParam(name, urlStr = window.location.search.substr(1)) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
			var r = urlStr.match(reg);
			if (r != null) {
				return unescape(r[2]);
			}
			return null;
		},
		navToResume(resume) {
			if (!resume._id) return false;
			window.open('http://cmzc.cc/admin/#/pages/talent/list/?_id=' + resume._id, '_blank');
		},
		navToProject(project) {
			window.open('http://cmzc.cc/admin/#/pages/project/list/?_id=' + project._id, '_blank');
		},
		async updateResume({
			resume,
			tid,
			force,
			from,
			checkname,
			company_id
		}) {
			console.log('小助手获取到简历信息：', resume, from, force, company_id, checkname);
			this.resumeData = resume;
			this.from = from;
			this.force = force;
			this.tid = tid || this.getUrlParam('fromuid', resume.link);
			this.resumeData.link = this.removeUrlParam(resume.link, 'fromuid');

			/**************如果要查询指定公司下的姓名 START*****************/
			if (checkname && company_id) {
				let name = resume.name?.split(' ')[0].trim();
				if (name.includes('先生') || name.includes('女士') || name.includes('**') || name.length < 2) {
					this.loading = false;
					this.postCheckOver();
					return false;
				}
				const result = await ajaxService.getTalentByName({
					name,
					company_id
				});
				if (result && result._id) {
					this.tid = result._id;
					this.force = true;
				} else {
					this.loading = false;
					this.postCheckOver();
					return false;
				}
			}
			/**************/
			if (this.tid && this.force) {
				this.force = false;
				return this.upload(this.tid);
			}
			/**********************************************************/
			if (!_.isEmpty(resume)) {
				this.repeatBtn();
			}
		},
		async batchMatch(data) {
			const company_ids = this.vcompanys?.map((item) => item._id);
			if (!company_ids || company_ids?.length == 0) return this.$message.error('请选择要关联的公司');
			const names = _.pluck(data.names, 'name');
			//const company_id = data.company_id;
			const company_id = company_ids.join(',');
			const result = await ajaxService.getBatchTalentByName({
				names,
				company_id
			});
			const list = result.map(talent => {
				const ndata = _.findWhere(data.names, {
					'name': talent.name
				});
				return {
					...ndata,
					_id: talent._id
				};
			})
			window.postMessage({
				type: 'talent_batch_match_success',
				data: {
					list
				}
			},
				'*'
			);
		},
		initListener() {
			const that = this;
			window.addEventListener('message', function ({
				data
			}) {
				if (data.type === 'resume') {
					console.log('小助手获取到简历信息：', data.data);
					// if(that.closeDialogBool)return false;
					that.closeDialogBool = false;
					$('.el-main.rwrap,.actwrap').show();
					that.updateResume(data.data);
				} else if (data.type === 'close_resume') {
					this.resumeData = {};
					$('.el-main.rwrap,.actwrap').hide();
					console.log('清除简历匹配数据3：');
					that.closeDialogBool = true;
				} else if (data.type == 'export') { } else if (data.type == 'talent_match_over') {
					that.matchOver();
				} else if (data.type === 'talent_batch_match') {
					that.batchMatch(data.data);
				}
			});
		},
		removeUrlParam(url = '', ref) {
			var str = '';
			if (url.indexOf('?') != -1) {
				str = url.substr(url.indexOf('?') + 1);
			} else {
				return url;
			}
			var arr = '';
			var returnurl = '';
			if (str.indexOf('&') != -1) {
				arr = str?.split('&');
				for (let i in arr) {
					if (arr[i]?.split('=')[0] != ref) {
						returnurl = returnurl + arr[i]?.split('=')[0] + '=' + arr[i]?.split('=')[1] + '&';
					}
				}
				return url.substr(0, url.indexOf('?')) + '?' + returnurl.substr(0, returnurl.length - 1);
			} else {
				arr = str?.split('=') || [];
				if (arr[0] == ref) {
					return url.substr(0, url.indexOf('?'));
				} else {
					return url;
				}
			}
		},
		async checkUserStatus(user) {
			/***************验证用户的状态****************/
			const result = await ajaxService.getUserData({
				_id: user?.user_id
			});
			if (!result || result.status != 0) {
				$('#resumeWrap').remove();
				this.$message.error('用户登录状态失效');
				return false;
			}
		},
		async checkLogin() {
			const user = $('body').data('user');
			this.checkUserStatus(user);
			const pictureData = $('body').data('picture') || {};
			this.userInfo = user;
			this.pictureList = pictureData.picture || []; //画像列表数据
			this.pictureFrom = pictureData.from || ''; //画像来源
			this.pictureId = pictureData._id || ''; //画像对应来源id
		}
	},
	mounted() {
		this.$nextTick(function () {
			$('#resumeWrap').draggable({
				handle: '#dragHeader,.r_open,.resume_main',
				//filter:'.relation',
				cancel: '.relation',
				stop(evt, data) {
					const { left, top } = data.position;
					localStorage.setItem('resumeLeft', left);
					localStorage.setItem('resumeTop', top);
				}
			});
			/*还原插件最初的位置*/
			const left = localStorage.getItem('resumeLeft');
			const top = localStorage.getItem('resumeTop');
			if (left && top) {
				$('#resumeWrap').css({
					left: left + 'px',
					top: top + 'px'
				});
			}
			//this.getRemoteCList();
		});
	},
	beforeCreate() { },
	created() {
		this.checkLogin();
		this.initListener();
		if (process.env.NODE_ENV != 'production') {
			this.resumeData = resumeData;
			this.repeatBtn();
		}
		if (window.location.href.includes('maimai')) {
			this.plateform = 'maimai';
		} else if (window.location.href.includes('zhaopin')) {
			this.plateform = 'zhaopin';
		} else if (window.location.href.includes('liepin')) {
			this.plateform = 'liepin';
		} else if (window.location.href.includes('zhipin')) {
			this.plateform = 'zhipin';
		}
		window.painter = this;
		const closeDialogBool = localStorage.getItem('closeDialogBool');
		this.closeDialogBool = closeDialogBool == 'true' ? true : false;
		const closePictureBool = localStorage.getItem('closePictureBool');

		this.closePictureBool = closePictureBool == 'true' ? true : false;

	}
};
</script>

<style lang="less">
* {
	margin: 0;
	padding: 0;
}

.otext {
	color: #909399;
	font-size: 12px;
	padding: 0 5px;

	.blue {
		color: #147fcc;
		font-weight: 600;
		margin-right: 2px;
		text-decoration: underline;
	}
}

.resume_wrap .btn_mini {
	color: #fff;
	background-color: #147fcc;
	display: inline-block;
	line-height: 1;
	padding: 5px 5px;
	border-radius: 5px;
	margin-top: -5px;

	&.btn_mini2 {
		background-color: #fff;
		border-color: #147fcc;
		color: #147fcc;
	}
}

.dtext {
	color: #147fcc;
}

.resume_wrap .rtitle {
	padding: 0px 5px 0px 5px;
	border-bottom: 1px solid #ccc;
	cursor: move;
	display: flex;
	width: 250px;
	justify-content: space-between;
	align-items: center;

	h5 {
		font-weight: bold;
		font-size: 14px;
	}

	.ainfo {
		display: flex;
		align-items: center;
		position: relative;

		img {
			width: 16px;
			height: 16px;
			object-fit: cover;
			display: inline-block;
			border-radius: 50%;
			border: 1px solid #147fcc;
		}

		span {
			position: relative;
			top: 2px;
			color: #606266;
			// font-weight: bold;
			margin-left: 2px;
			font-size: 12px;
		}
	}
}

.resume_wrap {
	z-index: 9999;
	border-radius: 5px;
	position: fixed;
	right: 66px;
	top: 20%;
	width: 250px;
	padding: 0px;
	background-color: #fff;
	border: 1px solid #ccc;

	.resume_main {
		cursor: move;
		width: 250px;
	}
}

.pselect {
	width: 100%;
	height: 30px;
	border: 1px solid #ded9d9;
	border-radius: 5px;
	color: #575555;

}

.el-dialog__body {
	padding: 10px 20px !important;
}

.picture_wraper {
	margin-top: 0px;
	padding: 5px 5px;
	border-top: 1px solid #ccc;
	min-height: 10px;

	.p_close {
		position: absolute;
		right: 0px;
		top: 0px;
		color: #407BF2;
		font-size: 13px;
		font-weight: bold;
		cursor: pointer;
	}

	.ptitle {
		position: relative;
		font-size: 13px;
	}

	&.picture_close ul.piclist {
		display: none;
	}

	.el-collapse-item__header {
		height: 30px;
		line-height: 30px;
	}

	.el-collapse-item__arrow {
		margin-right: 0px;
	}

	.el-collapse-item__content {
		padding-bottom: 5px;
	}

	.el-icon-arrow-right::before {
		display: inline-block;
		content: '>';
	}

	.p_collapse {}

	.ptitle {
		color: #000;
		font-weight: bold;
		font-size: 13px;
	}

	.piclist {
		list-style: none;
		margin-bottom: 0;

		li {
			line-height: 1.2;
		}

		li span {
			color: #606266;
			font-size: 12px;
			margin-right: 5px;
		}

		li em {
			font-size: 12px;
			color: #147fcc;
			display: inline-block;
		}
	}
}

.resume_wrap .avatar {
	width: 40px;
	border-radius: 5px;
}

.resume_wrap .el-empty {
	padding: 10px 0;

	.el-empty__image {
		width: 60px;
	}

	.el-empty__description p {
		font-size: 12px;
	}
}

.resume_wrap .split_line {
	display: none !important;
}

.resume_wrap .split_content {
	border-top: 1px solid #ccc;
	padding-top: 2px;
}

.resume_wrap .view_btn {
	font-weight: bold;
	color: #147fcc;
	cursor: pointer;
	font-weight: bold;
	text-decoration: underline;
}

.resume_wrap .el-input--suffix .el-input__inner {
	padding-right: 20px;
	padding-left: 5px;
}

.resume_wrap .el-input__suffix {
	right: -2px;
	top: 4px;
}

.resume_wrap .company {
	width: 50%;

	.el-input__inner {
		padding: 0 5px;
	}
}

.resume_wrap .similar .el-descriptions__header {
	margin: 5px 0;

	.el-descriptions__title {
		font-size: 12px;
	}
}

.resume_wrap .similar .el-descriptions__body {
	max-height: 300px;
	overflow: auto;

	.el-descriptions-item {
		font-size: 12px !important;
	}

	.el-descriptions-item__cell {
		line-height: 1;

		.el-descriptions-item__content {
			line-height: 1.2;
			//overflow: hidden;
			//text-overflow: ellipsis;
			//white-space: nowrap;
		}

		a {
			color: #147fcc;
			cursor: pointer;
			font-weight: bold;
			text-decoration: underline;
		}
	}
}

.resume_wrap .refresh {
	color: #147fcc;
	cursor: pointer;
	font-size: 11px;
	text-decoration: underline;
}

.resume_wrap .back_btn {
	display: block;
	margin-bottom: 5px;
	margin-top: -10px;
	color: #147fcc;
	cursor: pointer;
}

.resume_wrap .rwrap p.sinfo {
	//border-top: 1px solid #ccc;
	background: #f6f6f6;
	border-radius: 2px;
	padding: 4px;
	margin: 2px 0 0;
	line-height: 1.4;

	em {
		display: inline-block;
		width: 8px;
		height: 8px;
		border-radius: 50%;
		background-color: #147fcc;
	}
}

/****************************************/
.resume_wrap .rwrap {
	padding: 5px 5px;
	color: #666;
	font-size: 12px;
	max-height: 600px;
	overflow: auto;
	position: relative;
	width: 100%;
	display: block!important;
}

.resume_wrap .rwrap p {
	line-height: 1.6;
}

.resume_wrap em {
	color: #147fcc;
	font-weight: bold;
	display: inline-block;
	margin: 0 2px;
	font-style: normal;
	font-size: 14px;
}

.resume_wrap .uname {
	color: #000;
	font-weight: bold;
}

.resume_wrap .rwrap .tag {
	border-radius: 4px;
	padding: 2px 6px;
	line-height: 18px;
	font-size: 11px;
	line-height: 1.4;
	color: #147fcc;
	background-color: #fff;
	border: 1px solid #147fcc;
	margin: 2px;
	margin-bottom: 4px;

	display: inline-block;
}

.resume_wrap .relation {
	display: flex;
	justify-content: space-between;
	align-items: center;
	//flex-direction:column;
	padding-bottom: 10px;

	.rtit {
		color: #000;
		font-weight: bold;
		font-size: 11px;
	}

	&.relation2 {
		padding: 5px;

		.vselect {
			width: 150px;

			.vs__selected {
				position: relative;
				padding-right: 18px;
				max-width: 100px;
				font-size: 12px;
				line-height: 2;

				.vs__deselect {
					position: absolute;
					right: 5px;
					top: 7px;
				}
			}
		}

		.rtit {
			font-size: 11px;
		}
	}

	margin-bottom: 5px;

	.el-input--small .el-input__inner {
		height: 22px;
		line-height: 22px;
		font-size: 11px;
	}
}

/****************************************/
.resume_wrap .actwrap {
	cursor: move;
	padding: 5px 5px;
	border-top: 1px solid #ccc;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.resume_wrap .actwrap .btn {
	width: 46%;
	display: inline-block;
	padding: 5px 0;
	text-align: center;
	border-radius: 12px;
	font-size: 12px;
	cursor: pointer;
	line-height: 12px;

	&.disable {
		opacity: 0.4;
		pointer-events: none;
	}
}

.resume_wrap .btn1 {
	color: #fff;
	background-color: #147fcc;
	border: 1px solid #147fcc;
}

.resume_wrap .btn2 {
	color: #147fcc;
	background-color: #fff;
	border: 1px solid #147fcc;
}

.resume_wrap .btn3 {
	color: #fff;
	width: 100% !important;
	background-color: #147fcc;
	border: 1px solid #147fcc;
}

.resume_wrap .btn3.sbtn {
	padding: 5px 0;
	text-align: center;
	border-radius: 12px;
	font-size: 12px;
	margin: 10px 0 5px;
}

.vselect {
	position: relative;
	width: 116px;

	.vs__selected {
		line-height: 1;
		max-width: 70px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		display: inline-block;
	}

	.vs__dropdown-option {
		padding-left: 5px;
		padding-right: 5px;
	}

	.vs__search,
	.vs__search:focus {
		font-size: 12px;
		line-height: 1;
	}

	.vs__dropdown-menu {

		max-width: 300px;
		width: 200%;
		overflow-x: hidden;
		max-height: 200px;
	}

	.vs__selected-options {
		padding: 0;
	}

	&.hasrelation .vs__search {
		display: none;
	}

	&.vs--open .vs__search {
		display: block;
	}

	&.talent .vs__dropdown-menu {
		left: auto;
		right: 0;
	}

	.vs__dropdown-option--highlight {
		background: #dadad9;
	}
}

.hasrelation .el-input__suffix::after {
	content: '';
	display: block;
	position: absolute;
	width: 20px;
	height: 20px;
	top: -2px;
	right: 2px;
	background-repeat: no-repeat;
	background-position: center;
	background-size: 70%;
	pointer-events: none;
	z-index: 1;
	background-image: url();
}

.el-button--primary {
	background-color: rgb(64, 158, 255) !important;
}

.el-button--danger {
	background-color: #dd6161 !important;
}

.el-button--info {
	background-color: rgb(144, 147, 153) !important;
}

.resume_wrap .r_minus {
	color: #407BF2;
	font-size: 14px;
	text-decoration: underline;
	cursor: pointer;
	margin-left: 0px;
	font-weight: bold;
}

.app_wraper .r_open {
	cursor: pointer;
	display: inline-block;
	//width: 32px;
	border-radius: 50%;
	padding: 2px;
	text-align: center;
	font-size: 11px;
	color: #fff;
	cursor: pointer;
	display: none;
	height: 28px;
	line-height: 14px;
	width: 28px;
	padding: 4px;
	box-sizing: content-box;
	border-radius: 50%;
	background-color: #407BF2;
}

.app_wraper.close_dialog .r_open {
	display: block;
}

.app_wraper.close_dialog .resume_wrap {
	border-color: transparent;
	justify-content: flex-start;
	background-color: transparent;
	width: 40px;

}
</style>